package scau.mis4.chanyulin.dao;

import scau.mis4.chanyulin.entity.Temp;
import scau.mis4.chanyulin.tools.utils.DbUtils;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by cyl on 2017/12/5.
 * 温度DAO
 */
public class TempDao {

    /**
     * 获取所有温度记录
     * @return
     */
    public static List<Temp> getAll() {
        List<Temp> tempList = new LinkedList<>();
        String sql = "SELECT * FROM temp;";
        try {
            ResultSet rs = DbUtils.getStatement().executeQuery(sql);
            System.out.println("[sql] " + sql);
            while(rs.next()) {
                int id = rs.getInt("id");
                double temp1 = rs.getDouble("temp1");
                double temp2 = rs.getDouble("temp2");
                double temp3 = rs.getDouble("temp3");
                double temp4 = rs.getDouble("temp4");
                double temp5 = rs.getDouble("temp5");
                double temp6 = rs.getDouble("temp6");
                double avg = rs.getDouble("avg");
                Timestamp time = rs.getTimestamp("time");
                tempList.add(new Temp(id, temp1, temp2, temp3, temp4, temp5, temp6, avg, time));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return tempList;
    }

    /**
     * 添加温度记录
     * @return
     */
    public static void add(Temp temp) {
        double temp1 = temp.getTemp1();
        double temp2 = temp.getTemp2();
        double temp3 = temp.getTemp3();
        double temp4 = temp.getTemp4();
        double temp5 = temp.getTemp5();
        double temp6 = temp.getTemp6();
        double avg = temp.getAvg();
        DateFormat translator = new SimpleDateFormat("yyyyMMddHHmmss");
        String timeStr = translator.format(temp.getTime());
        StringBuffer sql = new StringBuffer("INSERT INTO temp VALUES(0, ");
        sql.append(temp1 + ", ").append(temp2 + ", ").append(temp3 + ", ")
            .append(temp4 + ", ").append(temp5 + ", ").append(temp6 + ", ")
            .append(avg + ", ").append(timeStr + ");");
        try {
            DbUtils.getStatement().executeUpdate(sql.toString());
            System.out.println("[sql] " + sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 清空所有温度记录
     * @return
     */
    public static void clearAll() {
        String sql = "TRUNCATE TABLE temp;";
        try {
            DbUtils.getStatement().executeUpdate(sql.toString());
            System.out.println("[sql] " + sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
